from importlib import import_module
import threading


class Metric:
    def __init__(self, key, value):
        self.key = key
        self.value = value


class Monitor:
    def __init__(self, collectors, backends):
        self.collectors = []
        self.backends = []

        for collector in collectors:
            self.load_collector(collector)

        for backend in backends:
            self.load_backend(backend)

    def start(self):
        while True:
            for collector in self.collectors:
                metrics = collector.run()
            for backend in self.backends:
                backend.send(metrics)
            threading.Event().wait(3)

    def shutdown(self):
        pass

    def load_collector(self, plugin):
        """
        monitor.plugin.snmp_collector.SNMPCollector
        """
        pkg, cls = plugin.rsplit('.', 1)
        mod = import_module(pkg)
        instance = getattr(mod, cls)()
        self.collectors.append(instance)

    def load_backend(self, plugin):
        """
        monitor.plugin.logger_backend.LoggerBackend
        """
        pkg, cls = plugin.rsplit('.', 1)
        # pkg = monitor.plugin.logger_backend
        # cls = LoggerBackend
        mod = import_module(pkg)
        # 等价于
        # import monitor.plugin.logger_backend as mod
        instance = getattr(mod, cls)()
        # 等价于 instance = LoggerBackend()
        self.backends.append(instance)
